package com.azzcs.v2.offer12;

/**
 * @Author: azzcs
 * @Date: 2021/10/8 上午11:43
 */
public class Solution {
    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (words[0] == board[i][j]) {
                    if (search(i, j, board, words)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean search(int i, int j, char[][] board, char[] words) {
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != words[0]) {
            return false;
        }
        char temp = board[i][j];
        board[i][j] = '1';
        if (words.length == 1) {
            return true;
        }
        char[] chars = new char[words.length - 1];
        System.arraycopy(words, 1, chars, 0, chars.length);
        if (search(i + 1, j, board, chars) ||
                search(i - 1, j, board, chars) ||
                search(i, j + 1, board, chars) ||
                search(i, j - 1, board, chars)) {
            return true;
        } else {
            board[i][j] = temp;
            return false;
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.exist(new char[][]{
                {'A', 'A'}
        }, "AAA"));
    }
}
